package vip.xiaonuo.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Reactor;
import reactor.event.Event;
import reactor.function.Consumer;
import vip.xiaonuo.modular.facegrouporgrelate.entity.FacegroupOrgRelate;
import vip.xiaonuo.modular.facegrouporgrelate.service.FacegroupOrgRelateService;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.topic.SysOrgEventTopic;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import static reactor.event.selector.Selectors.$;

@Service
@Slf4j
public class SysOrgAddListener implements Consumer<Event<SysOrg>>, InitializingBean {

    @Autowired
    private Reactor reactor;

    @Resource
    private FacegroupOrgRelateService relateService;

    @Override
    public void afterPropertiesSet() throws Exception {
        reactor.on($(SysOrgEventTopic.ORG_ADD), this);
    }

    @Override
    public void accept(Event<SysOrg> sysOrgEvent) {
        SysOrg org = sysOrgEvent.getData();
        // 判断新增机构的父机构是否与人脸分组关联
        Long pid = org.getPid();
        List<FacegroupOrgRelate> relates = relateService.list(new LambdaQueryWrapper<FacegroupOrgRelate>().eq(FacegroupOrgRelate :: getOrgId , pid));

        List<FacegroupOrgRelate> toSave = new ArrayList<>();
        if(relates.size()>0) {
            for (FacegroupOrgRelate relate : relates) {
                FacegroupOrgRelate rel = new FacegroupOrgRelate();
                rel.setFaceGroupId(relate.getFaceGroupId());
                rel.setOrgId(org.getId());
                toSave.add(rel);
            }
            relateService.saveBatch(toSave);
        }

    }
}
